package com.chengcang.api.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chengcang.api.modules.sys.dao.SysTenantMenuDao;
import com.chengcang.api.modules.sys.dto.SysTenantMenuDTO;
import com.chengcang.api.modules.sys.entity.SysTenantMenuEntity;
import com.chengcang.api.modules.sys.service.SysTenantMenuService;
import com.chengcang.common.service.impl.CrudServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 客户菜单
 *
 * @author zhanli
 * @since 1.0.0 2023-01-05
 */
@Service
public class SysTenantMenuServiceImpl extends CrudServiceImpl<SysTenantMenuDao, SysTenantMenuEntity, SysTenantMenuDTO> implements SysTenantMenuService {

    @Override
    public QueryWrapper<SysTenantMenuEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<SysTenantMenuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assign(Long tenantId, Long[] menuIds) {
        // 如果已存在，先清除
        baseDao.delete(new LambdaQueryWrapper<SysTenantMenuEntity>()
                .eq(SysTenantMenuEntity::getTenantId, tenantId));

        List<SysTenantMenuEntity> list = new ArrayList<>();
        for (Long menuId : menuIds) {
            SysTenantMenuEntity sysTenantMenu = new SysTenantMenuEntity();
            sysTenantMenu.setMenuId(menuId);
            sysTenantMenu.setTenantId(tenantId);
            list.add(sysTenantMenu);
        }
        insertBatch(list);
    }
}